﻿var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var httpget = require('http');
var bodyParser = require('body-parser');
var session = require('express-session');
var s_db = require('./dbwrap_construct_1.js');
var fs = require('fs');
var SMSClient = require('@alicloud/sms-sdk');
var child_process = require('child_process');
var methods = require('methods');
var tcpcache = require('./tcpcache.min.js');
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var md5 = require("md5");
var pub_config = require('./construct_config.js');
var request = require('request');
//在线
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Credentials", true);
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", 'BIM');
    // res.header("Content-Type", "application/json;charset=utf-8");

    next();
});
app.use(express.static(__dirname + '/app'));
http.listen(9069, function () {
    console.log('info',"listening on *:9069 construct");
});
app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: false,
    cookie: {
        maxAge: 1000 * 60 * 30//过期时间设置(单位毫秒)
    }
}));
app.use(function (req, res, next) {
    var url = req.url;
    if (url == '/userlogin' || url.indexOf('/sensor_data') >= 0){
        next();
        return;
    }
    if (!req.session.user){
        res.send({ret:-3,info:"session过期"});
        return;
    }else if (req.session.user){
        next();
    }
});
// 通过启动子进程启动tcpserver
var process_start = child_process.fork(__dirname+'/process_8052.js');
process_start.on('message', function (m) {
    console.log('PARENT got message:', m);
}); 
function server_db() {
    return s_db;
}
// ************************函数*****************************
// ********************施工管理接口******************************
// **********************公用接口********************************
function post_select_data(req,res,tablename,fields) {
    var page = null;
    if (req.body.page) {
        page = req.body.page;
    } else {
        page = req.body.currentPage;
    }
    var limit = req.body.rows;
    var sidx = req.body.sidx;
    var sord = req.body.sord;
    if (sidx == null)
        sidx = 1;  
    if (page == null)
        page = 1;
    if (limit == null)
        limit = 10;    
    server_db().db_info_type_page(req,fields,tablename, page, limit,sidx,sord,function(ret,info){
            info.ret = ret;
            // if (tablename == 'logfile') {
            //     console.log('info',info);
            // }           
            res.send(info);   
    });
};
function isJSON(str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                return true;
            } catch(e) {
                return false;
            }
        }else{
            return false;
        }
}
// 项目：1：代表项目编辑权限、2：代表设备编辑权限、4：代表查看权限
function project_power(power,num){
        var arr_pro = [];
        if (isJSON(power) == true){
            power = JSON.parse(power);
            for (var i = 0; i < power.length; i++) {
                var projectid = power[i].projectid;
                var current_power = power[i].power;
                if ((current_power & num) == num) {
                  arr_pro.push(projectid);
                }
            }
        }        
        return arr_pro;
}
// **********************前台接口********************************
// 账号密码登录
app.post('/userlogin', function (req, res) {
    var id = req.body.id;
    var pass = req.body.pass;
    var tablename = 'user';
    if (id == null || pass == null) {
        res.sendStatus(404);
        return;
    }
    else {
        pass = md5(pass);
        var query = {
            id:"="+id,
            pass:"="+pass
        };
        server_db().db_get_detailuser(tablename,query, function (ret, info,power) {
            if (ret == -1){
                res.send({ret:-1});
            }
            else if (ret == 0) {
                res.send({ret:0});
            }
            else if (ret == 1) {
                req.session.user = id;               
                if (info.fid == '1'){//管理员
                    req.session.power = 'all';
                    req.session.fid = id;
                }else{//普通用户
                    req.session.fid = info.fid;
                    req.session.power = power;
                }                
                res.send({ ret: 1,info: info,power:req.session.power});               
            }
        });
    }
});
app.get('/logout', function (req, res) {
    req.session.user = null;
    req.session.error = null;
    res.redirect('/login.html');
});
app.get('/session_user', function (req, res) {
    // console.log(req.session.fid);
    res.send({ret:1,user:req.session.user,fid:req.session.fid,power:req.session.power});
});
// **********************后台接口*************************************

// ***************************get接口***************************************
// 获取设备类型
app.get('/device_types', function (req, res) {
    var info = pub_config.device_types;
    res.send({ ret: 1, info: info });
});
/* 类型获取 
   req.params.type可能值：
   notice_type:通知类型(处理类型)
   par_types：参数类型
   device_types：设备类型
*/
app.get('/public_types/:type',function(req,res){
    var type = req.params.type;
    if (type == null || type == '') {
        res.send({ret:-1,info:'no type'});
        return;
    }
    var info = pub_config[type];
    res.send({ret:1,info:info});
})
// 获取设备类型的名称
app.get('/device_types/:id', function (req, res) {
    var info = pub_config.device_types;
    var id = req.params.id;
    if (id == null || id == '') {
        res.send({ ret: -1, info: '没有id' });
        return;
    }
    var name = '';
    for (var i = 0; i < info.length; i++) {
        var obj = info[i];
        if (id == obj.id) {
            name = obj.name;
            break;
        }
    }
    res.send({ ret: 1, info: name });
});
// 查询详情数据 (url?a==1) 单条数据  
app.get('/detail/:table', function (req, res) {
    var query = req.query;
    var tablename = req.params.table;
    if (tablename == null || query == null) {
        res.sendStatus(404);
        return;
    }
    else {
        server_db().db_get_detail(tablename,query, function (ret, info) {
            res.send({ret:ret,info:info});
        });
    }
});
//2.0 获取数据不分页  url?a==1
app.get("/list_nopage/:table", function (req, res) {
    var table = req.params.table;
    if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    var fields = '*';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
            req.query.fid = req.session.fid;
     
    }else{
        var arr_pro = project_power(power,4);
        if (arr_pro.length <= 0) {
            res.send({ret:1,info:[]});
            return;
        }                    
        if(table == "project"){//通过项目id获取项目列表
            req.field_arr = arr_pro; 
            req.field = 'id';               
        }
        else if(table == "device"){//通过项目id获取设备列表
            req.field_arr = arr_pro; 
            req.field = 'projectid';
        }
        else if (table == 'log') {//通过设备id获取log列表
            // 获取设备id
            server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                 if (ret == 1) {
                    var deviceid_arr = [];
                    for (var i = 0; i < info.length; i++){
                        var obj = info[i];
                        deviceid_arr.push(obj.deviceid);
                    }
                    if (deviceid_arr.length > 0) {
                        server_db().db_select_list('deviceid', deviceid_arr,req.query, fields ,table,'time','desc', function(ret1,info1){
                             res.send({ ret: ret1, info: info1 });
                        });
                    }else{
                        res.send({ret:1,info:[]});
                    }
                 }else{
                    res.send({ ret: ret, info: info});
                 }
            });
            return;
        }
    }
    server_db().db_select_list(req.field,req.field_arr,req.query, fields, table,null,null, function(ret,info){
         res.send({ ret: ret, info: info });
    });
});

// 2.1 不分页  url?a==1
app.get("/select_idname/:table", function (req, res) {
    var table = req.params.table;
    var fields = 'id,name';
     if (table == null || table == "") {
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.query.fid = req.session.fid;
    }else{
        var arr_pro = project_power(power,4);
        if (table == 'project') {
            if (arr_pro.length > 0) {
               server_db().db_select_where_in('id',arr_pro,fields,table,function(ret,info){
                  res.send({ret:1,info:info});
               })
            }else{
                  res.send({ret:1,info:[]})
            }
            return;           
        }else{
            req.query.fid = req.session.fid;
        }
    }
    server_db().db_select_list(null,null,req.query, fields, table,null,null, function(ret,info){
         res.send({ ret: ret, info: info });
    });
});
// 2.1 不分页  获取所有的设备
app.get("/select_deviceid", function (req, res) {
    var table = 'device';
    var fields = 'id,deviceid';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.query.fid = req.session.fid;
    }
    server_db().db_select_list(null,null,req.query, fields, table,null,null, function(ret,info){
         res.send({ ret: ret, info: info });
    });
});
// 不分页历史数据曲线：查询指定字段 url?deviceid=1&time=2017-01-01,2017-02-02
// log表
app.get("/history_data",function(req,res){
    var table = 'log';
    var fields = 'press,temp,time';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        // 获取设备id
        req.query.fid = req.session.fid;
        server_db().db_select_list(null, null,req.query, fields ,table,'time','asc', function(ret1,info1){
             res.send({ ret: ret1, info: info1 });
        });
    }else{
            var arr_pro = project_power(power,4);
            if (arr_pro.length <= 0) {
                res.send({ret:1,info:[]});
                return;
            }
            // 获取设备id
            server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                 if (ret == 1) {
                    var deviceid_arr = [];
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        deviceid_arr.push(obj.deviceid);
                    }
                    if (deviceid_arr.length > 0) {
                        server_db().db_select_list('deviceid', deviceid_arr,req.query, fields ,table,'time','asc', function(ret1,info1){
                             res.send({ ret: ret1, info: info1 });
                        });
                    }else{
                        res.send({ret:1,info:[]});
                    }                  
                 }else{
                    res.send({ret:ret,info:info});
                 } 
            });
    }
    
})
app.get("/history_data_yk",function(req,res){
    var table = 'yk_datasub';
    var fields = 'deviceid,value,time,sensor_num,point_num,dm';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        // 获取设备id
        req.query.fid = req.session.fid;
        server_db().db_select_list(null, null,req.query, fields ,table,'time','asc', function(ret1,info1){
             res.send({ ret: ret1, info: info1 });
        });
    }else{
            var arr_pro = project_power(power,4);
            if (arr_pro.length <= 0) {
                res.send({ret:1,info:[]});
                return;
            }
            // 获取设备id
            server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                 if (ret == 1) {
                    var deviceid_arr = [];
                    for (var i = 0; i < info.length; i++) {
                        var obj = info[i];
                        deviceid_arr.push(obj.deviceid);
                    }
                    if (deviceid_arr.length > 0) {
                        server_db().db_select_list('deviceid', deviceid_arr,req.query, fields ,table,'time','asc', function(ret1,info1){
                             res.send({ ret: ret1, info: info1 });
                        });
                    }else{
                        res.send({ret:1,info:[]});
                    }                  
                 }else{
                    res.send({ret:ret,info:info});
                 } 
            });
    }
    
})

// 获取实时数据
app.post("/actual_data/:port",function(req,res){
    var port = parseInt(req.params.port);
    var power = req.session.power;
    // console.log(req.query)
    if (port == null || port == '') {
        port = 8051;
    }
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'administrator'){
        var a=null,b=null;//超级管理员查看所有设备或筛选的项目的设备
        if(req.query.projectid != undefined && req.query.projectid != "="){
            a = 'projectid';
            b = [];
            b.push(req.query.projectid.replace("=",""));
        }
        // 获取所有的设备id
        server_db().db_select_list(a,b,null,'id,deviceid,zone,status','device',null,null,function(ret,info){
            if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(port,deviceid_arr);
                    for(var j=0;j<data.length;j++){
                        for(var k=0;k<info.length;k++){
                            if(data[j].deviceid == info[k].deviceid){
                                data[j].zone = info[k].zone;
                                data[j].status = info[k].status;
                            }
                        }
                    }
                    res.send({ret:1,info:data});
                }else{
                    res.send({ret:1,info:[]});
                }
            }else{
                res.send({ret:ret,info:info});
            }          
        })      
    }else if (power == 'all') {//管理员
        //获取设备id
        var a=null,b=null;//管理员查看自己创建的设备或筛选的自己项目的设备
        if(req.query.projectid != undefined && req.query.projectid != "="){
            a = 'projectid';
            b = [];
            b.push(req.query.projectid.replace("=",""));
        }
        // console.log("query "+a+b)
        // req.query.projectid = req.query.projectid == undefined ? "=" : req.query.projectid;
        server_db().db_select_list(a,b,{fid:req.session.fid}, 'id,deviceid,zone,status', 'device',null,null, function(ret,info){
           if (ret == 1){
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                // console.log('deviceid',deviceid_arr);
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(port,deviceid_arr);
                    for(var j=0;j<data.length;j++){
                        for(var k=0;k<info.length;k++){
                            if(data[j].deviceid == info[k].deviceid){
                                data[j].zone = info[k].zone;
                                data[j].status = info[k].status;
                            }
                        }
                        
                    }
                    // console.log(data);
                    res.send({ret:1,info:data});
                }else{
                    res.send({ret:1,info:[]});
                }
                
            }else{
                   res.send({ret:ret,info:info});
            }
        });
    }else if (isJSON(power) == true){//普通用户
        var arr_pro = project_power(power,4);
        if (arr_pro.length <= 0) {
            res.send({ret:1,info:[]});
            return;
        }
        var b=arr_pro;//普通用户 查看某项目的实时数据，或查看该权限的设备的实时数据。
        if(req.query.projectid != undefined && req.query.projectid != "="){
            b = [];
            b.push(req.query.projectid.replace("=",""));
        }
        // 获取设备id
        server_db().db_select_where_in('projectid', b, 'id,deviceid,zone,status', 'device', function(ret,info){
             if (ret == 1) {
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                if (deviceid_arr.length > 0) {
                    var data = tcpcache.get_port_device_data(port,deviceid_arr);
                    for(var j=0;j<data.length;j++){
                        for(var k=0;k<info.length;k++){
                            if(data[j].deviceid == info[k].deviceid){
                                data[j].zone = info[k].zone;
                                data[j].status = info[k].status;
                            }
                        }  
                    }
                    res.send({ret:1,info:data});
                }else{
                    res.send({ret:1,info:[]});
                }
             }else{
                res.send({ret:ret,info:info});
             }
        });
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
});


// 获取表的所有列
app.get('/table_columns/:table',function(req,res){
    var table = req.params.table;
    if (table == null || table == ""){
        res.sendStatus(404);
        return;
    }
    server_db().db_table_columns(table,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
//获取设备总数，报警设备，正常设备
app.get('/device_count',function(req,res){
    
    var power = req.session.power;
    var total = 0;
    var warn = 0;
    var ok = 0;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'administrator'){//超级管理员
        server_db().db_get_count(null,null,'deviceid','device',null,function(ret,info){
            if (ret == 1) {
                total = info;
                server_db().db_get_count(null,null,'deviceid','device',{fid:'='+req.session.fid,status:'0'},function(ret1,info1){
                    if (ret1 == 1) {
                        warn = info1;
                        ok = total - warn;
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }else{
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }
               })
            }
       })
    }else if (power == 'all') {//管理员
       server_db().db_get_count(null,null,'deviceid','device',{fid:'='+req.session.fid},function(ret,info){
            if (ret == 1) {
                total = info;
                server_db().db_get_count(null,null,'deviceid','device',{fid:'='+req.session.fid,status:'0'},function(ret1,info1){
                    if (ret1 == 1) {
                        warn = info1;
                        ok = total - warn;
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }else{
                        res.send({ret:1,total:total,warn:warn,ok:ok})
                    }
               })
            }
       })
    }else if (isJSON(power) == true){//有权限普通用户
        var arr_pro = project_power(power,4);
        if (arr_pro.length <= 0) {
            res.send({ret:1,total:total,warn:warn,ok:ok});
            return;
        }
        server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
            if (ret == 1) {               
                var deviceid_arr = [];
                for (var i = 0; i < info.length; i++) {
                    var obj = info[i];
                    deviceid_arr.push(obj.deviceid);
                }
                total = deviceid_arr.length;
                if (deviceid_arr.length <= 0) {
                    res.send({ret:1,total:total,warn:warn,ok:ok})
                }else{
                    server_db().db_get_count('deviceid',deviceid_arr,'deviceid','device',{fid:'='+req.session.fid,status:'0'},function(ret1,info1){
                        // console.log(ret1,info1);
                        if (ret1 == 1) {
                            warn = info1;
                            ok = total - warn;
                            res.send({ret:1,total:total,warn:warn,ok:ok})
                        }else{
                            res.send({ret:1,total:total,warn:warn,ok:ok})
                        }
                   })
                }               
            }
       })
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
        
})
/* 特定接口（不通用,宝鸡项目）：接收传感器数据:存入log表中,其他的数据存储到其他表中
  转发报警
  req.body数据格式为
  {
    data:{
      deviceid:'123456',
      press:'99',
      temp:'20'
    }
    data_ext:{
    
    }
  }
*/
app.post('/sensor_data/:port', function (req, res) {
    var port = parseInt(req.params.port);
    var data = req.body.data;
    var data_ext = req.body.data_ext;
    if (data_ext != null && data_ext.press_unit != null && data != null) {
        data.press_unit = data_ext.press_unit;
    }
    console.log(data,data_ext);
    tcpcache.tcpcallback(port, data, data_ext, function (r_port, r_data) {
        // 存入数据库
        console.log('save',r_port,r_data);
        server_db().db_get_detail_field('device', { port: r_port, deviceid: r_data.deviceid }, 'fid,projectid', function (ret, info) {
            if (ret == 1) {
                r_data.fid = info.fid;
                r_data.projectid = info.projectid;
                // 判断是否触发报警，存入报警日志表（warn_report）
                var notice_query = {
                    deviceid: '=' + r_data.deviceid,
                    fid: '=' + info.fid
                }
                var str = ' and value is not null';
                server_db().db_select_list2(null, null, notice_query, '*', 'warn_config', null, null, str, function (ret3, info3) {
                    // console.log(ret3,info3);
                    if (ret3 == 1 && info3.length > 0) {
                        var warn = []; //一个报警即报警 都不报警才不报警
                        for (var i = 0; i < info3.length; i++) {
                            var warninfo = info3[i];
                            var warn_type = warninfo.warn_type;
                            var value = warninfo.value;
                            var fieldname = warninfo.fieldname;
                            // 判断是否触发报警
                            if (r_data[fieldname] != null) {
                                var iswarn = is_warn(r_data[fieldname], value, warn_type, fieldname, fieldname);
                                // console.log(iswarn);
                                warn[i] = iswarn;
                                if (iswarn == true) {
                                    // 存入报警日志表
                                    var obj = {};
                                    obj.deviceid = r_data.deviceid;
                                    obj.fid = info.fid;
                                    obj.projectid = info.projectid;
                                    obj.warn_type = warn_type;
                                    obj.fieldname = fieldname;
                                    
                                    server_db().db_get_detail_field('device',{port:r_port,deviceid:r_data.deviceid},'deviceid,status',function(ret7,info7){
                                        // console.log('77777777777777777777')
                                        // console.log(ret7,info7)
                                        if(ret7 == 1){
                                            if(info7.status == "0"){//报警状态-->更新warn_report
                                                // server_db().db_info_update(obj,notice_query,'warn_report',function (ret6, info6) {
                                                //     console.log('更新报警信息 ',ret6,info6)
                                                // });
                                            }else if(info7.status == "1"){//正常状态-->warn_report添加一条报警
                                                server_db().db_info_insert(obj,'warn_report',function(ret2,info2){
                                                    console.log('插入报警信息 ',ret2,info2)
                                                })
                                            }
                                        }
                                    })
                                }
                            }

                            if(warn.length != 0){
                                // console.log(warn)
                                var warn_status = 1;
                                if(warn.length == 1){
                                    warn_status = warn[0] == true ? "0" : "1";
                                }else if(warn.length == 2){
                                    warn_status = warn[0] || warn[1] == true ? "0" : "1";
                                }
                                // console.log(warn_status)
                                // 修改设备表的状态
                                server_db().db_info_update({status:warn_status},notice_query,'device',function (ret4, info4) {
                                    // console.log(ret4,info4) 
                                    console.log(notice_query.deviceid +" "+ warn_status)
                                });
                            }
                        }
                    }
                })
                //历史数据
                // console.log('r_data.status = '+r_data.status)
                if(r_data.status == undefined && r_data.status != 0 && r_data.temp !=undefined){
                    var log_data = {
                        deviceid: r_data.deviceid,
                        projectid: info.projectid,
                        fid: info.fid,
                        temp: r_data.temp,
                        press: r_data.press,
                        time: r_data.time,
                        press_unit: r_data.press_unit
                    }
                    server_db().db_info_insert(log_data,'log',function(ret1,info1){
                    //   console.log('log',ret1,info1);
                      res.send({ret:ret1,info:info1});
                    })
                }
                
            } else {
                // console.log('no deviceid, no save');
                res.send({ ret: 1, info: 'no save' });
            }
        })
    })
});
/*钱波新增加一个接口: 油库的传感器数据
  转发报警
  req.body数据格式为
  {
    data:{
      deviceid:'123456',
      name:'press',
      value:'99'
    }
    data_ext:{
    
    }
  }
*/
app.post('/sensor_data_1/:port', function (req, res) {
    var port = parseInt(req.params.port);
    var data = req.body.data;
    var data_ext = req.body.data_ext;
    // console.log(data,data_ext);
    tcpcache.tcpcallback(port, data, null, function (r_port, r_data) {
        // 存入数据库
        // console.log('save',r_port,r_data);
        server_db().db_get_detail_field('view_device_project', { port: r_port, deviceid: "=" + r_data.deviceid }, 'fid,projectid,type,devicename,procode', function (ret, info) {
            if (ret == 1) {
                r_data.fid = info.fid;
                r_data.projectid = info.projectid;
                // console.log(r_data);
                // 判断是否触发报警，存入报警日志表（warn_report）
                var notice_query = {
                    deviceid: '=' + r_data.deviceid,
                    fid: '=' + info.fid
                }
                var str = ' and value is not null';
                server_db().db_select_list2(null, null, notice_query, '*', 'warn_config', null, null, str, function (ret3, info3) {
                    // console.log(ret3,info3);
                    if (ret3 == 1 && info3.length > 0) {
                        var warn = []; //一个报警即报警 都不报警才不报警
                        for (var i = 0; i < info3.length; i++) {
                            var warninfo = info3[i];
                            var warn_type = warninfo.warn_type;
                            var value = warninfo.value;
                            var fieldname = warninfo.fieldname;
                            // 判断是否触发报警
                            var iswarn = is_warn(r_data.value, value, warn_type, fieldname, r_data.name);
                            // console.log(iswarn);
                            warn[i] = iswarn;
                            if (iswarn == true) {
                                // 通知用户
                                warninfo.devname = info.devicename;
                                warninfo.devtype = info.type;
                                warninfo.code = info.procode;
                                if (warninfo.notice_type == 4) {
                                    notice_user(warninfo, r_data);
                                }
                                // 存入报警日志表
                                var obj = {};
                                obj.deviceid = r_data.deviceid;
                                obj.fid = info.fid;
                                obj.projectid = info.projectid;
                                obj.warn_type = warn_type;
                                obj.fieldname = fieldname;

                                server_db().db_get_detail_field('device',{port:r_port,deviceid:r_data.deviceid},'deviceid,status',function(ret7,info7){
                                    // console.log('77777777777777777777')
                                    // console.log(ret7,info7)
                                    if(ret7 == 1){
                                        if(info7.status == "0"){//报警状态-->更新warn_report
                                            // server_db().db_info_update(obj,notice_query,'warn_report',function (ret6, info6) {
                                            //     console.log('更新报警信息 ',ret6,info6)
                                            // });
                                        }else if(info7.status == "1"){//正常状态-->warn_report添加一条报警
                                            server_db().db_info_insert(obj,'warn_report',function(ret2,info2){
                                                console.log('插入报警信息 ',ret2,info2)
                                            })
                                        }
                                    }
                                })

                            }
                            
                        }
                        if(warn.length != 0){
                            console.log(warn)
                            var warn_status = 1;
                            if(warn.length == 1){
                                warn_status = warn[0] == true ? "0" : "1";
                            }else if(warn.length >= 1){
                                for(var w=0;w<warn.length;w++){
                                    warn_status = warn_status || warn[w];
                                }
                                warn_status = warn_status == true ? "0" : "1";
                            }
                            // console.log(warn_status)
                            // 修改设备表的状态
                            server_db().db_info_update({status:warn_status},notice_query,'device',function (ret4, info4) {
                                // console.log(ret4,info4) 
                                console.log(notice_query.deviceid.replace("=","") +" 报警状态："+ warn_status)
                            });
                        }
                    }
                })
                //历史数据
                server_db().db_info_insert(r_data, 'yk_datasub', function (ret, info) {
                    res.send({ ret: ret, info: info });
                })
            } else {
                //  console.log('no deviceid, no save');
                res.send({ ret: 1, info: 'no save' });
            }
        })
    })
});


//数据传送并且分析
app.post('/sensor_data_analyse', function (req, res) {
    console.log(req.body);
    res.send({ ret: 1 });
});
/*
 功能： 判断是否触发报警,返回true或false
 value1：接收到传感器值，
 value2: 报警表的报警值，
 warn_type: 报警表的报警类型，
      1：上限报警
      2：下限报警
      3：其他报警
      4：等级报警
 fieldname1:报警表的报警字段，
 fieldname2:接收到的报警字段
*/
// var arr = [1,2,3];
// var arr1 = JSON.stringify(arr);
// var arr2 = JSON.parse(arr1);
// console.log(arr1);
// console.log(arr2[0]);
function is_warn(value1,value2,warn_type,fieldname1,fieldname2){
   // console.log(value1,value2,warn_type,fieldname1,fieldname2);
   var flag = false;
   if (fieldname1 == fieldname2 && value1 != null && value2 != null && (typeof value1 == 'string') && (typeof value2 == 'string')) {
        var dm = fieldname1 == "temp" ? 1 : 2;
        if (value1.indexOf("[") >= 0 && value1.indexOf("]") >= 0
            && value2.indexOf("[") >= 0 && value2.indexOf("]") >= 0) {
            value1 = value1.replace("[","").replace("]","");
            value1 = value1.split(",");
            value2 = value2.replace("[","").replace("]","");
            value2 = value2.split(",");
        }
        if (warn_type == 1) {
            if (Array.prototype.isPrototypeOf(value1) == true &&
            Array.prototype.isPrototypeOf(value2) == true) {//如果是数组
                for (var i = 0; i < value1.length; i++) {
                    if(parseFloat(value1[i]) > parseFloat(value2[i])*dm){
                        flag = true;
                        break;
                    }
                }
            }else if (parseFloat(value1) > parseFloat(value2)*dm){
                flag = true;
            }
        }else if (warn_type == 2) {
            if (Array.prototype.isPrototypeOf(value1) == true &&
            Array.prototype.isPrototypeOf(value2) == true) {//如果是数组
                for (var i = 0; i < value1.length; i++) {
                    if(parseFloat(value1[i]) < parseFloat(value2[i])*dm){
                        flag = true;
                        break;
                    }
                }
            }else if (parseFloat(value1) < parseFloat(value2)*dm){
                flag = true;

            }
        }else if (warn_type == 3) {

        }else if (warn_type == 4) {

        }
    }
   return flag;
}
/*
 功能：报警通知
 input:报警通知类型
 data:报警的数据信息
*/
function notice_user(input, input_data) {
    /*
      input.notice_type:
      0: 不通知
      1: 短信通知
      2: 公众号通知
      3: 短信、公众号通知
      4: 转发给别的服务
      5: 反馈处理
    */
    // console.log(input);
    var query = {
        fid: '=' + input.fid,
        warn_grade: '0,' + input.warn_grade
    }
    switch (input.notice_type) {
        case 0://不通知
            break;
        case 4://转发通知          
            if (input.postaddress != null && input.postaddress != '') {
                var json = {
                    equipment_id: input.deviceid,
                    equipment_name: input.devname,
                    equipment_type: input.devtype,
                    type: "FIRST",
                    status: "异常",
                    warn_infor: input_data.name + "报警,值为" + input_data.value
                    // warn_time:input.time
                }
                var post_data = {
                    type: "WARNING_INFO",
                    code: input.code,//"YC_XT_XF"
                    // downtime:input.time,
                    busicode: random_time(true),
                    data: json
                }
                // console.log(post_data);
                PostData2(post_data, input.postaddress, function (ret, info) {
                    // console.log(ret,info);
                })
            }
            break;
        default:

    }
}
// ***************************post接口 业务层***************************************
// 分页查询  url?a==1
// 对表的分页查询：信息列表 select:(search,select)
app.post('/list/select/:table', function (req, res) {
    // log_start.control("debug",req.body);
    // console.log(req.query);
    // console.log("power",req.session.fid,req.session.power);
    var table = req.params.table;
    if (table == null || table == ""){
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if(power == 'all'){
            req.query.fid = req.session.fid;
    }else{
            var arr_pro = project_power(power,4);
            if (arr_pro.length <= 0) {
                res.send({ret:1,info:[]});
            }else{
                if(table == "project"){//通过项目id获取项目列表
                    req.field_arr = arr_pro; 
                    req.field = 'id';               
                }
                else if(table == "device"){//通过项目id获取设备列表
                    req.field_arr = arr_pro; 
                    req.field = 'projectid';
                }
                else if (table == 'log') {//通过设备id获取log列表
                    // 获取设备id
                    server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                         if (ret == 1) {
                            var deviceid_arr = [];
                            for (var i = 0; i < info.length; i++) {
                                var obj = info[i];
                                deviceid_arr.push(obj.deviceid);
                            }
                            if (deviceid_arr.length > 0){
                                req.field_arr = deviceid_arr; 
                                req.field = 'deviceid';
                                post_select_data(req, res, table,null);    
                            }else{
                                res.send({ret:1,info:[]});
                            }
                         }
                    });
                    return;
                }else{
                    req.query.fid = req.session.fid;
                }
            }                     
            
    }
    post_select_data(req, res, table,null);        
});
// 添加一条数据
app.post('/data/:table',function(req,res){
    var table = req.params.table;
    var c = Object.keys(req.body);
    if (table == null || table == "" || c.length <= 0){
        res.sendStatus(404);
        return;
    }
    if (table == 'user') {
        req.body.pass = md5('111111');
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.body.fid = req.session.fid;
    }else{
        if (table == 'logfile') {
            req.body.fid = req.session.fid;
        }else if (table == 'device'){
            var arr_pro = project_power(power,2);
            var index = arr_pro.indexOf(parseInt(req.body.projectid));
            req.body.fid = req.session.fid;
            if (index < 0){
                res.send({ret:-1,info:'没有权限或者没有绑定现有项目'});
                return;
            }
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }     
    }
    server_db().db_info_insert(req.body,table, function (ret, info) {
           if (ret == 1) {
              res.send({ret:ret,info:info});
           }else{
              res.send({ret:-1,info:info});
           }
            
    });
});
// 添加多条数据 body: [{name:1},{name:2}]
app.post('/data_mul/:table',function(req,res){
    var table = req.params.table;
    if (table == null || table == "" || JSON.stringify(req.body) == '{}'){
        res.sendStatus(404);
        return;
    }
    server_db().db_info_insert_mul(table,req.body,function(ret,info){
        res.send({ret:ret,info:info});
    })
});

// 创建协议(建表)
// var define ={
//    tableName: "alarm7",//报警信息表
//    fields: {
//        id: { des: "序号", type: "INT(11) PRIMARY KEY AUTO_INCREMENT" },
//        type: { des: "类型", type: "varchar(110)" },
//        des: { des: "描述", type: "varchar(110)" },
//        condition1: { des: "报警条件json", type: "varchar(210)" },
//        grade: { des: "等级", type: "varchar(110)" }
//    }
// }
app.post('/create_protocol',function(req,res){
    var c = Object.keys(req.body);
    if (c.length <= 0){
        res.sendStatus(404);
        return;
    }
    var table = 'protocol';
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        req.body.fid = req.session.fid;        
    }else{
        res.send({ret:-4,info:'没有权限'});
        return; 
    }
    server_db().db_info_insert(req.body,table, function (ret, info) {
           if (ret == 1) {
              var define ={
                   tableName: "protocol_"+info,//报警信息表
                   fields: {
                       id: { des: "序号", type: "INT(11) PRIMARY KEY AUTO_INCREMENT" }
                   }
              }
              server_db().db_create_table(define,function(ret1,info1){
                    res.send({ret:ret1,info:info1});
              })
           }else{
              res.send({ret:-1,info:info});
           }
            
    });   
});
// 添加列
// body:{name:"testfieldss",type:"int(12)",des:"this is a test",first:true}
app.post('/add_column/:table',function(req,res){
   var table = req.params.table;
    if (table == null || table == "" || req.body == null){
        res.sendStatus(404);
        return;
    }
    server_db().db_add_column(table,req.body,function(res,info){
        res.send({ret:ret,info:info});
    })
});
// ***************************put接口***************************************
// 下发查询的接口
app.post('/query_device',function(req,res){
    var deviceid = req.body.deviceid;
    if (deviceid == null || deviceid == '') {
        res.sendStatus(404);
        return;
    }
    req.body.cmd = 'read';
    // console.log(req.body);
    var data = JSON.stringify(req.body);
    // var message = Buffer.from('00000000');
    client.send(data, 0, data.length, 8051, 'localhost');
    // client.on('message', function(msg){
    //     console.info('msg')
    // });
    var data = tcpcache.get_port_device_data_1(8051,deviceid);
    res.send({ret:1,info:data});
});
// 参数设置的接口
app.put('/edit_device',function(req,res){
    var deviceid = req.query.deviceid;
    var id = req.query.id;
    var table = 'device';
    if (deviceid != null && deviceid.indexOf('=') >= 0) {
        deviceid = deviceid.match(/=(\S*)/)[1];
    }
    if (deviceid == null || deviceid == '' || id == '' || id == null) {
        res.sendStatus(404);
        return;
    }
    var write_data = req.body;
    // var cun_data = {};
    // Object.assign(cun_data,req.body);
    // var message = Buffer.from('00000000');
    // client.on('message', function(msg){
    //     console.info('msg')
    // });
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;    
    }else if (power == 'all') {
        req.body.fid = req.session.fid; 
    }else if (power == 'administrator'){

    }else if (isJSON(power) == true){//有权限普通用户
            var arr_pro = project_power(power,2);         
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                     if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = req.query.id;                        
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        // console.log(power,arr_pro,deviceid_arr,req.query.id,str);
                        if (index >= 0) {
                            server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                               res.send({ret:ret,info:info}); 
                               if (ret == 1) {
                                  write_data.deviceid = deviceid;
                                  write_data.cmd = 'write';
                                  var data = JSON.stringify(write_data);
                                  client.send(data, 0, data.length, 8051, 'localhost');
                               }
                            });
                        }else{
                            res.send({ret:-4,info:'没有权限'});
                        }
                     }
                });
            }
            return;
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
       res.send({ret:ret,info:info}); 
       if (ret == 1) {
          write_data.deviceid = deviceid;
          write_data.cmd = 'write';
          var data = JSON.stringify(write_data);
          client.send(data, 0, data.length, 8051, 'localhost');
       }
    });
});
// 修改密码 编辑一条数据 url?id==5
app.put('/modifypass',function(req,res){
   var table = 'user';
   var pass = req.body.pass;
   var oldpass = req.body.oldpass;
   var c = Object.keys(req.query);
   if (pass == null || pass == '' || c.length <= 0 || oldpass == null || oldpass == '') {
      res.sendStatus(404);
      return;
    }
    delete req.body.oldpass;
    req.body.pass = md5(pass);
    oldpass = md5(oldpass);
    server_db().db_get_detailuser(table,req.query, function (ret, info,power) {
            if (ret == -1){
                res.send({ret:-1});
            }
            else if (ret == 0) {
                res.send({ret:0});
            }
            else if (ret == 1) {
                if (info.pass == oldpass) {
                    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                       res.send({ret:ret,info:info}); 
                    });
                    
                }else{
                    res.send({ret:-1,info:'原始密码错误'})
                }                            
            }
    });
});
// 编辑一条数据 url?id==5
app.put('/data/:table',function(req,res){
    var table = req.params.table;
    var c = Object.keys(req.query);
    if (table == null || table == "" || req.body == null || c.length <= 0){
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        if (table == 'user') {
            req.body.fid = req.session.fid;
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }        
    }else if (power == 'all') {
        if (table == 'user' && (req.query.id == ("="+req.session.fid) || req.query.id == req.session.fid)) {
            req.body.fid = '1';
        }else{
            req.body.fid = req.session.fid;
        }
        
    }else{//普通用户
        if (table == 'device'){
            var arr_pro = project_power(power,2);
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                     if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = req.query.id;                        
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        if (index >= 0) {
                            server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                               res.send({ret:ret,info:info}); 
                            });
                        }else{
                            res.send({ret:-4,info:'没有权限'});
                        }
                     }
                });
            }
            return;
        }else if(table == 'project'){
            var arr_pro = project_power(power,1);
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                var str = req.query.id;                        
                if (str != null && str.indexOf('=') >= 0) {
                    str = str.match(/=(\S*)/)[1];
                }
                var index = arr_pro.indexOf(parseInt(str));
                if (index >= 0) {
                    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
                       res.send({ret:ret,info:info}); 
                    });
                }else{
                    res.send({ret:-4,info:'没有权限'});
                }
            }
            return;
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }
    }
    server_db().db_info_update(req.body,req.query,table,function (ret, info) {
       res.send({ret:ret,info:info}); 
    });
});

// 修改表的列
app.put('/column/:table/:columnname',function(req,res){
    var table = req.params.table;
    var column = req.params.columnname;
    if (table == null || table == "" || req.body == null || column == null){
        res.sendStatus(404);
        return;
    }
    server_db().db_edit_column(table,column,req.body,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
// ***************************delete接口***************************************
// 删除一条数据 url?id==123
app.delete('/data/:table',function(req,res){
    var table = req.params.table;
    var query = req.query;
    if (table == null || table == ""){
        res.sendStatus(404);
        return;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        
    }else{
        if (table == 'device'){
            var arr_pro = project_power(power,2);
            if (arr_pro.length <= 0) {
                res.send({ret:-4,info:'没有权限'})
            }else{
                // 获取设备表的id
                server_db().db_select_where_in('projectid', arr_pro, 'id,deviceid', 'device', function(ret,info){
                     if (ret == 1) {
                        var deviceid_arr = [];
                        for (var i = 0; i < info.length; i++) {
                            var obj = info[i];
                            deviceid_arr.push(obj.id);
                        }
                        var str = query.id;                        
                        if (str != null && str.indexOf('=') >= 0) {
                            str = str.match(/=(\S*)/)[1];
                        }
                        var index = deviceid_arr.indexOf(parseInt(str));
                        if (index >= 0) {
                            server_db().db_info_delete(query,table, function (ret, info) {
                               res.send({ret:ret,info:info}); 
                            });
                        }else{
                            res.send({ret:-4,info:'没有权限'});
                        }
                     }
                });
            }
            return;
        }else{
            res.send({ret:-4,info:'没有权限'});
            return;
        }       
    }
    server_db().db_info_delete(query,table, function (ret, info) {
       res.send({ret:ret,info:info}); 
    });
});
// 删除多行数据 url?field=['a','b']
app.delete('/data_mul/:table',function(req,res){
    var table = req.params.table;
    var query = req.query;
    if (table == null || table == "" || JSON.stringify(query) == '{}'){
        res.sendStatus(404);
        return;
    }
    var field,arr;
    for (var key in query) {
        field = key;
        arr = query[key];
    }
    server_db().db_info_delete_mul(table,field,arr,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
// 删除一个协议(删除协议，删除协议的数据表)
app.delete('/sensor/protocol',function(req,res){
    var table = 'protocol';
    var query = req.query;
    var table2 = table+'_';
    var c = Object.keys(req.query);
    if (c.length <= 0 || query.id == null){
        res.sendStatus(404);
        return;
    }
    if (query.id[0] == "=") {
        var len =  query.id.length;
        table2 += query.id.substr(1,len-1);
    }else{
        table2 += query.id;
    }
    var power = req.session.power;
    if (power == '' || power == '0' || power == null) {//没有角色的普通用户
        res.send({ret:-4,info:'没有权限'});
        return;
    }else if (power == 'all') {
        
    }else{
        res.send({ret:-4,info:'没有权限'});
        return;
    }
    server_db().db_info_delete(query,table, function (ret, info) {
        if (ret == 1) {
            server_db().db_delete_table(table2,function(ret1,info1){
                res.send({ret:ret1,info:info1});
            })
        }else{
            res.send({ret:-1,info:info});
        }
    });
    
});
// 删除表中的一列
app.delete('/column/:table/:column',function(req,res){
    var table = req.params.table;
    var column = req.params.column;
    if (table == null || table == '' || column == null || column == '') {
        res.sendStatus(404);
        return;
    }
    server_db().db_delete_column(table,column,function(ret,info){
        res.send({ret:ret,info:info});
    })
});
// ********************************函数******************************************
function random_time(flag) {
    var str = '';
    var oDate = new Date(); //实例一个时间对象；
    str += oDate.getFullYear();   //获取系统的年；
    var month = oDate.getMonth() + 1;   //获取系统月份，由于月份是从0开始计算，所以要加1
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    str += month;
    var strDate = oDate.getDate(); // 获取系统日，
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    str += strDate;
    var hour = oDate.getHours(); //获取系统时，
    if (hour >= 0 && hour <= 9) {
        hour = "0"+hour;
    }
    str += hour;
    var min = oDate.getMinutes(); //分
    if (min >= 0 && min <= 9) {
        min = "0"+min;
    }
    str += min;
    var sen = oDate.getSeconds(); //秒 
    if (sen >= 0 && sen <= 9) {
        sen = "0"+sen;
    }
    str += sen; //秒    
    // 6位随机数
    if (flag == true) {
        for (var i = 0; i < 6; i++) {
            str += Math.floor(Math.random() * 10);
        }
    }   
    return str;
}


function PostData2(bodystr, url,cb) {
    var jsonheaders = {
        'Content-Type': 'application/json;charset=utf-8'
    };
    var options = {
        url: url,
        method: 'POST',
        json:true,
        body: bodystr,
        headers: jsonheaders
    };
    request(options, function(error, response, data) {
        if (!error && response.statusCode == 200) {
            if (cb) {
                cb(200,data); 
            }
            
        }else{
            console.log(error);
        }
    });
}

